#!/bin/sh
#
# Part of Gerrit Code Review (https://www.gerritcodereview.com/)
#
# Copyright (C) 2019 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


# To enable this hook:
# - copy this file or content to ".git/hooks/pre-commit"
# - (optional if you copied this file) make it executable: `chmod +x .git/hooks/pre-commit`

set -ue

# gitroot, default to .
gitroot=$(git rev-parse --show-cdup)
gitroot=${gitroot:-.};

# eslint
eslint=${gitroot}/node_modules/eslint/bin/eslint.js

# Run eslint over changed frontend code
CHANGED_UI_FILES=$(git diff --cached --name-only --diff-filter=ACM -- '*.js' '*.html' | grep 'polygerrit-ui') && true
if [ "${CHANGED_UI_FILES}" ]; then
  if $eslint --fix ${CHANGED_UI_FILES}; then
    # Add again in case lint fix modified some files
    git add ${CHANGED_UI_FILES}
    exit 0
  else
    echo "Failed to fix all linter issues.";
    exit 1
  fi
else
  echo "No UI files changed"
  exit 0
fi